package com.example.ivideo_2211a.fg

import FytVideoAdapter
import android.view.View
import androidx.fragment.app.viewModels
import com.example.common.mvi.BaseFragment
import com.example.ivideo_2211a.R

import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.ivideo_2211a.databinding.FragmentFYTBinding
import com.example.ivideo_2211a.fyt.FYTViewModel
import com.example.ivideo_2211a.fyt.FYTIntent
import com.example.ivideo_2211a.fyt.FYTViewState
import com.example.ivideo_2211a.model.FtyTopeEntity

import com.example.ivideo_2211a.fyt.FtyTypeAdapter


class FYTFragment() : BaseFragment<FragmentFYTBinding, FYTViewModel, FYTIntent, FYTViewState>() {

	override val viewModel: FYTViewModel by viewModels()
	private lateinit var typeAdapter: FtyTypeAdapter
	private lateinit var videoAdapter: FytVideoAdapter
	private var selectedTypeId: String? = null

	override fun getLayoutId(): Int = R.layout.fragment_f_y_t

	override fun setupViews() {
		setupTypeRecyclerView()
		setupVideoRecyclerView()
		setupSwipeRefresh()
		setupErrorView()
		// 初始加载
		sendIntent(FYTIntent.LoadTypes)
	}

	private fun setupTypeRecyclerView() {
		typeAdapter = FtyTypeAdapter { type ->
			onTypeSelected(type)
		}
		binding.top.apply {
			adapter = typeAdapter
			layoutManager = LinearLayoutManager(requireContext(), LinearLayoutManager.HORIZONTAL, false)
		}
	}

	private fun onTypeSelected(selectedType: FtyTopeEntity) {
		if (selectedType.id == selectedTypeId) return
		selectedTypeId = selectedType.id
		val updatedTypes = viewModel.viewState.value.types.map { it.copy(isSelected = it.id == selectedType.id) }
		typeAdapter.submitList(updatedTypes)
		// 切换类型时刷新视频列表
		sendIntent(FYTIntent.SelectType(selectedType))
	}

	private fun setupVideoRecyclerView() {
		videoAdapter = FytVideoAdapter { video ->
			// 跳转到详情
			val videoDataJson = com.google.gson.Gson().toJson(video)
			com.alibaba.android.arouter.launcher.ARouter.getInstance()
				.build("/playvideo/PlayVideoActivity")
				.withString("videoDataJson", videoDataJson)
				.navigation()
		}
		binding.list.apply {
			adapter = videoAdapter
			layoutManager = GridLayoutManager(requireContext(), 2)
			addOnScrollListener(object : RecyclerView.OnScrollListener() {
				override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
					super.onScrolled(recyclerView, dx, dy)
					val layoutManager = recyclerView.layoutManager as GridLayoutManager
					val visibleItemCount = layoutManager.childCount
					val totalItemCount = layoutManager.itemCount
					val firstVisibleItemPosition = layoutManager.findFirstVisibleItemPosition()
					val currentState = viewModel.viewState.value
					if (!currentState.isLoadingMore && currentState.hasMore &&
						(visibleItemCount + firstVisibleItemPosition) >= totalItemCount - 3) {
						selectedTypeId?.let { channelId ->
							sendIntent(FYTIntent.LoadMoreVideos(channelId, currentState.currentPage + 1))
						}
					}
				}
			})
		}
	}

	private fun setupSwipeRefresh() {
		binding.swipeRefreshLayout.setOnRefreshListener {
			sendIntent(FYTIntent.RefreshTypes)
		}
	}

	private fun setupErrorView() {
		binding.errorTextView.setOnClickListener {
			sendIntent(FYTIntent.LoadTypes)
		}
	}

	override fun renderViewState(state: FYTViewState) {
		typeAdapter.submitList(state.types)
		videoAdapter.submitList(state.videos)
		binding.progressBar.visibility = if (state.isLoading) View.VISIBLE else View.GONE
		binding.swipeRefreshLayout.isRefreshing = state.isRefreshing
		binding.errorTextView.visibility = if (state.error != null && state.videos.isEmpty()) View.VISIBLE else View.GONE
		binding.list.visibility = if (state.videos.isNotEmpty()) View.VISIBLE else View.GONE
		
		// 处理加载更多状态
		if (state.isLoadingMore) {
			// 可以在这里显示底部加载指示器
			// 例如：binding.loadMoreProgressBar.visibility = View.VISIBLE
		}
	}
}